import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/models/delivery_setting_data.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class DeliveryProvider extends ChangeNotifier {
  DeliverySettingData data;

  Future<Result<DeliverySettingData>> initData() async {
    try {
      var res = await api.queryDeliver();
      if (!res.successful()) {
        return Result.error(res.msg);
      }
      data = res.data;

      if (data.takeoutCostSettingFormList.length == 0) {
        data.takeoutCostSettingFormList.add(TakeoutCostSettingFormList.fromJson({}));
      }

      notifyListeners();

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  setFreeDelivery(bool flag) {
    data.freeDelivery = flag ? 1 : 0;
    notifyListeners();
  }

  addDeliveryRule() {
    data.takeoutCostSettingFormList.add(TakeoutCostSettingFormList.fromJson({}));
    notifyListeners();
  }

  removeDeliveryRule(TakeoutCostSettingFormList rule) {
    if (data.takeoutCostSettingFormList.length == 1) {
      return;
    }
    data.takeoutCostSettingFormList.remove(rule);
    notifyListeners();
  }

  update() async {
    var flag = data.takeoutCostSettingFormList.any((item) => item.costAmount == null || item.targetValue == null);
    if (!data.isFreeDelivery && flag) {
      toast('请填写完整配送规则');
      return;
    }

    try {
      showLoadingToast();
      if (data.freeDeliveryAmount == null) {
        data.freeDeliveryAmount = -1;
      }
      var res = await api.updateDeliver(data);

      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('修改成功');
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }
}
